// pages/goods/details/index.js
const fetchGoodDetails = require('../../../services/good/fetchGoodDetails');
const userModel = require('../../../model/user');

Page({
  data: {
    product: null,  // 用于存放商品详情数据
    currentImageIndex: 0, 
    isMember: false,
    showPopup: false,
    showBuyButton: false,
    showParameterPopup: false,
  },

  onShareAppMessage() {
    return {
      title: "美酒城市",
      path: `/pages/goods/details/index?id=${this.data.product.id}`,
    }
  },
  
  // 页面加载时获取商品详情
  onLoad(options) {
    const wineId = options.id;  // 从 URL 参数获取 wineId
    const userData = userModel.getUserData();

    // 判断用户角色是否为VIP会员
    if (userData.info.role !== 'GUEST') {
      this.setData({ isMember: true });
    }
    this.setData({ showBuyButton: true });
    this.getProductDetails(wineId);  // 获取商品详情
  },

  // 获取商品详情
  async getProductDetails(id) {
    const productData = await fetchGoodDetails(id);
    if (productData) {
      this.setData({
        product: productData
      });
    } else {
      wx.showToast({
        title: '商品信息加载失败',
        icon: 'none'
      });
    }
  },

  // 打开参数详情弹窗
  openParameterPopup() {
    this.setData({
      showParameterPopup: true
    });
  },

  // 关闭参数详情弹窗
  closeParameterPopup() {
    this.setData({
      showParameterPopup: false
    });
  },

  // 图片切换
  handleImageChange(e) {
    this.setData({
      currentImageIndex: e.currentTarget.dataset.index
    });
  },

  // 返回按钮处理
  handleBack() {
    wx.navigateBack();
  },

  handleBuyNow() {
    this.setData({
      showPopup: true
    });
  },

  handleClosePopup() {
    this.setData({
      showPopup: false,
    });
  },

  handleCloseParameterPopup() {
    this.setData({
      showParameterPopup: false,
    });
  },

  // 确认下单
  handleConfirmOrder(orderData) {
    console.log('确认下单：', orderData);
  
    const app = getApp();
    app.globalData.orderData = orderData.detail;
    
    // 跳转到订单确认页面
    wx.navigateTo({
      url: '/pages/order/order-confirm/index'
    });
  }
});
